using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SmartLink.Domain.Entity;
using SmartLink.Domain.ExpandEntity.Oragnization;
using SmartLink.Domain.IServices;
using SmartLink.IRepository;
using SmartLink.EnumLibrary;
using SmartLink.Infrastructure.Cache;
using SmartLink.DTOS;

namespace SmartLink.Domain.Services
{
    public class BIZ_OrganizationServices : IBIZ_OrganizationServices
    {
        private IBIZ_OrganizationRepo _iBIZ_OrganizationRepo;
        private IBIZ_OrganizationDeptRepo _iBIZ_OrganizationDeptRepo;
        private IPER_RoleGroupRepo _IPER_RoleGroupRepo;
        private IPER_MenuPermissionsRoleRepo _IPER_MenuPermissionsRoleRepo;
        private IPER_ActionPermissionsRoleRepo _IPER_ActionPermissionsRoleRepo;
        private IPER_DataPermissionsRepo _IPER_DataPermissionsRepo;
        private ISYS_UserRepo _ISYS_UserRepo;
        public BIZ_OrganizationServices(IBIZ_OrganizationRepo iBIZ_OrganizationRepo,
                                        IBIZ_OrganizationDeptRepo iBIZ_OrganizationDeptRepo,
                                        IPER_RoleGroupRepo iPER_RoleGroupRepo,
                                        IPER_MenuPermissionsRoleRepo iPER_MenuPermissionsRoleRepo,
                                        IPER_ActionPermissionsRoleRepo iPER_ActionPermissionsRoleRepo,
                                        IPER_DataPermissionsRepo iPER_DataPermissionsRepo,
                                        ISYS_UserRepo iSYS_UserRepo
                                        )
        {
            _iBIZ_OrganizationRepo = iBIZ_OrganizationRepo;
            _iBIZ_OrganizationDeptRepo = iBIZ_OrganizationDeptRepo;
            _IPER_RoleGroupRepo = iPER_RoleGroupRepo;
            _IPER_MenuPermissionsRoleRepo = iPER_MenuPermissionsRoleRepo;
            _IPER_ActionPermissionsRoleRepo = iPER_ActionPermissionsRoleRepo;
            _IPER_DataPermissionsRepo = iPER_DataPermissionsRepo;
            _ISYS_UserRepo = iSYS_UserRepo;
        }

        public OperationResult AddOrganization(BIZ_Organization org)
        {
            //if (_iBIZ_OrganizationRepo.CheckExistByOrgName(org.OrganizationName) || _iBIZ_OrganizationRepo.CheckExistByOrgName(org.OrganizationShorterName))
            //    return new OperationResult(OperationResultType.ParamError, "公司名称已经存在！");

            org.OrganizationStatus = OrgStatusEnum.启用;
            org.CreateTime = DateTime.Now;
            org.Creator = CurrentUser.Current.UserId;

            if (org.ParentID.HasValue)
            {
                org.ROID = _iBIZ_OrganizationRepo.GetRootOrganizationId(org.ParentID.Value);
                _iBIZ_OrganizationRepo.Add(org);
                return new OperationResult(OperationResultType.Success);
            }
            else
            {
                return AddRootOrganization(org);
            }
        }

        private OperationResult AddRootOrganization(BIZ_Organization org)
        {
            var id = _iBIZ_OrganizationRepo.Add(org);
            //建根组织回写ROID
            if (org.ROID == default(int))
            {
                org.ROID = org.ID;
                _iBIZ_OrganizationRepo.Update(org);
            }
            _IPER_RoleGroupRepo.AddDefaultRole(org.ID);
            return new OperationResult(OperationResultType.Success);
        }

        public bool DeleteOrganization(int orgId)
        {
            DbTransaction dbTranscation = _iBIZ_OrganizationRepo.TranCreate();
            try
            {
                //先不删除
                return false;
                _iBIZ_OrganizationRepo.DeleteLogic(orgId, dbTranscation);
                //删除部门
                _iBIZ_OrganizationDeptRepo.DeleteByOrgId(orgId);
                //删除公司下的用户
                _ISYS_UserRepo.DeleteUserByOrgId(orgId);
                //删除公司下的角色
                _IPER_RoleGroupRepo.DeleteRoleByOrgId(orgId);

                dbTranscation.Commit();
            }
            catch (Exception ex)
            {
                dbTranscation.Rollback();
                return false;
            }
            return true;
        }

        public bool UpdateOrganization(BIZ_Organization organizationDTO)
        {
            return _iBIZ_OrganizationRepo.Update(organizationDTO);
        }

        public bool CheckExistByOrgName(string orgName)
        {
            return _iBIZ_OrganizationRepo.CheckExistByOrgName(orgName);
        }

        public IList<OrganizationManageExpand> GetOrganizationList(int status, int district, string keyValue, int pageIndex, int pageSize, bool isSearchTotal, out int count)
        {
            return _iBIZ_OrganizationRepo.GetOrganizationList(status, district, keyValue, pageIndex, pageSize, isSearchTotal, out count);
        }
        /// <summary>
        /// 组织机构列表（不分页）
        /// </summary>
        /// <returns></returns>
        public IList<BIZ_Organization> OrganizationListinfo()
        {
            var list = _iBIZ_OrganizationRepo.OrganizationListinfo();
            return list;
        }
        public SingleOragnizationInfoExapnd GetSingleOrganization(int orgId)
        {
            return _iBIZ_OrganizationRepo.GetSingleOrganization(orgId);
        }

        public IEnumerable<BIZ_Organization> GetOrgDescendants(int topOid, bool withSelf = false)
        {
            return _iBIZ_OrganizationRepo.GetDescendants(topOid, withSelf);
        }

        public static bool InitDisabledCompanyIds()
        {
            var ids = Repository.BIZ_OrganizationRepo.GetDisabledCompanyIds();
            return Infrastructure.Cache.DisabledCompanysCache.AddDisabledCompanys(ids.ToArray());
        }

        public BIZ_Organization GetOrganization(int id)
        {
            return _iBIZ_OrganizationRepo.GetById(id);
        }

        public IEnumerable<BIZ_Organization> GetRootOrganizations()
        {
            return _iBIZ_OrganizationRepo.GetRootOrganizations();
        }

        public IEnumerable<BIZ_Organization> GetCompanyTreeData(int? topOid)
        {
            if (!topOid.HasValue)
            {
                var rootOrgs = _iBIZ_OrganizationRepo.GetRootOrganizations();
                var allOrgs = new List<BIZ_Organization>();
                foreach (var org in rootOrgs)
                {
                    allOrgs.AddRange(_iBIZ_OrganizationRepo.GetDescendants(org.ID, true));
                }
                return allOrgs;
            }
            else
            {
                return _iBIZ_OrganizationRepo.GetDescendants(topOid.Value, true);
            }
        }
    }
}
